<template>
    <div class="div-height-left">
        <el-card ref="card" class="box-card">
            <div class="tree-div" style="height: 35px">
                <el-checkbox v-model="deptExpand" style="margin-top: 7px;"
                             @change="handleCheckedTreeExpand($event, 'tree')">
                    展开/折叠
                </el-checkbox>
                <el-checkbox v-if="showCheckbox" v-model="deptNodeAll" style="margin-top: 7px;"
                             @change="handleCheckedTreeNodeAll($event)">
                    全选/全不选
                </el-checkbox>
            </div>
            <div class="group-menu-tree" :style="{height:height}">
                <el-empty v-if="!orgId" description="暂无科室数据，请先选择所属机构"></el-empty>
                <template v-else>
                    <el-input v-model="filterText" placeholder="输入关键字进行过滤">
                    </el-input>

                    <el-tree ref="tree" :data="data" :expand-on-click-node="false" :filter-node-method="filterNode"
                             :highlight-current=true :props="defaultProps" :show-checkbox="showCheckbox"
                             class="filter-tree"
                             default-expand-all node-key="id" @node-click="nodeClick">
                    </el-tree>
                </template>
            </div>
        </el-card>
    </div>
</template>

<script lang="ts" setup>

import {listDeptTree} from '@/api/system/dept'
// import { useUserStoreHook } from "@/store/modules/user"

// const useUserStore = useUserStoreHook();
// 登录用户信息
// const userInfo = <UserInfoBusi>useUserStore.user.userInfo

const emits = defineEmits(['listDeptTree', 'treeClick'])
const tree = ref()
let filterText = ref("")
let data = ref([])
let defaultProps = ref({
    children: 'children',
    label: 'label'
})
let thisExcessHeight = ref(0)
let style = ref({
    height: 'calc(100% - 150px)'
})
let deptExpand = ref(true)
let deptNodeAll = ref(false)
let deptCount = ref(0)
const props = defineProps({
    orgId: String,
    showCheckbox: Boolean,
    defaultCheckedKeys: {
        type: Array,
        default: () => []
    },
    height: {
        type: String,
        default: "400px"
    }
})

watch([filterText, thisExcessHeight], (newVal, _oldVal) => {
    tree.value.filter(newVal[0])
    style.value = {
        height: 'calc(100% - ' + newVal[1] + 'px)'
    }
})
watch(() => data.value, (_newValue, _oldValue) => {
    nextTick(() => {
        if (props.defaultCheckedKeys.length > 0) {
            judgmentAllSelection(props.defaultCheckedKeys)
        }
    })
}, {immediate: true, deep: true})
watch(() => props.orgId, (newValue, _oldValue) => {
    getListDept(newValue)
}, {
    deep: true,
    // 立即的
    immediate: true,
})


watch(() => props.defaultCheckedKeys, (newValue, _oldValue) => {
    judgmentAllSelection(toRaw(newValue))
}, {deep: true})

/** 判断是否全选 */
function judgmentAllSelection(defaultCheckedKeys: any) {
    if (!defaultCheckedKeys) {
        // el-tree设置、取消选中状态（高亮）
        return tree.value.setCurrentKey(null)
    }
    deptNodeAll.value = deptCount.value === defaultCheckedKeys.length;
    defaultCheckedKeys.map((i: any, _n) => {
        //根据i获取tree中的节点
        let node = tree.value.getNode(i);
        if (node) {
            nextTick(() => {
                //设置某个节点的勾选状态
                tree.value.setChecked(node, true, false);
            })
        }
    })
}

/** 查询科室列表 */
function getListDept(orgId: string | undefined) {
    listDeptTree({'delFlag': '0', 'status': '0', 'orgId': orgId}).then(res => {
        data.value = res.data.list
        deptCount.value = res.data.deptList
        emits('listDeptTree', res.data.list)
    })
}

/** 搜索 */
function filterNode(value, data) {
    if (!value) return true
    return data.label.indexOf(value) !== -1
}

/** 树节点点击事件 */
function nodeClick(a, _b, _c) {
    emits('treeClick', a)
}

/** 获取勾选节点 */
function getCheckedKeys() {
    return tree.value.getCheckedKeys().concat(tree.value.getHalfCheckedKeys());
}

// 树权限（展开/折叠）
function handleCheckedTreeExpand(value, _type) {
    let treeList: any = data.value;
    for (let i = 0; i < treeList.length; i++) {
        tree.value.store.nodesMap[treeList[i].id].expanded = value;
    }
}

// 树权限（全选/全不选）
function handleCheckedTreeNodeAll(value) {
    tree.value.setCheckedNodes(value ? data.value : []);
}

/** 清空选中节点 */
function clearTheSelection() {
    tree.value.setCheckedKeys([]);
}

defineExpose({
    clearTheSelection,
    getCheckedKeys,
    judgmentAllSelection
})
</script>

<script lang="ts">
export default {
    name: "DeptTree"
}
</script>

<style lang="scss" scoped>
.box-card {
    overflow-y: auto;
    height: calc(100% - 70px);
}

.aab {
    height: calc(100% - 150px);
}

:deep(.el-card__body) {
    height: 100%;
}
</style>
